package View;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.CopyOption;
import java.util.*;
import java.util.Map.Entry;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;

import Model.*;
import Controler.*;

/**
 * Class Cwindow
 *
 */
class Cwindow extends JFrame implements KeyListener {


	public Cwindow() 
	{
	}

	public void keyPressed(KeyEvent e) {
	}
	public void keyReleased(KeyEvent e) {
	}
	public void keyTyped(KeyEvent e) {            
	}
}

/**
 * Classe Calculette qui créée le graphisme ainsi que les évènements liés à celle-ci
 * @author Maxou
 */
public class Interface extends JFrame implements ActionListener{

	public HashMap<String, JTextField> listTextFields;
	private HashMap<String, JLabel> listLabels;

	private JLabel labelContact;


	private BufferedImage profilePicture;
	private JLabel labelProfilePicture;
	private String picturePath;

	private JButton buttonAddContact;
	private JButton buttonSaveContact;
	private JButton buttonDeleteContact;

	private JPanel panelGeneral;
	private JPanel panelPhoto;
	private JPanel panelName;
	private JPanel panelPhotoAndName;
	private JPanel panelInfo;
	private JPanel panelAddress;
	private JPanel panelContactButtons;
	private JPanel panelContact;
	private JPanel panelList;
	private JPanel panelListAndButtons;
	private JPanel panelPersonalPhones;
	private JPanel panelProPhones;
	private JPanel panelEmail;
	private JPanel panelOther;
	private JPanel panelGroupAndHomePage;

	private JTable table;
	private DefaultTableModel model;

	private JScrollPane scrollingContactList;

	public ArrayList listOfContacts;

	float n;
	int c;

	private void loadHashMaps()
	{
		listTextFields = new HashMap<String, JTextField>();
		listLabels = new HashMap<String, JLabel>();
	}

	public void loadLabels() {

		loadHashMaps();

		JLabel labelFirstName = new JLabel();
		JLabel labelLastName = new JLabel();
		JLabel labelHomeAddress = new JLabel();
		JLabel labelCompanyAddress = new JLabel();
		JLabel labelPersonalMobilePhone = new JLabel();
		JLabel labelPersonalHomePhone = new JLabel();
		JLabel labelProMobilePhone = new JLabel();
		JLabel labelProOfficePhone = new JLabel();
		JLabel labelHomePage = new JLabel();
		JLabel labelProEmail = new JLabel();
		JLabel labelPersonalEmail = new JLabel();
		JLabel labelOtherIM = new JLabel();
		JLabel labelOtherSkype = new JLabel();
		JLabel labelGroup = new JLabel();

		listLabels.put(Model.FIRST_NAME, labelFirstName);
		listLabels.put(Model.LAST_NAME, labelLastName);
		listLabels.put(Model.HOME_ADDRESS, labelHomeAddress);
		listLabels.put(Model.COMPANY_ADDRESS, labelCompanyAddress);
		listLabels.put(Model.PERSONAL_MOBILE_PHONE, labelPersonalMobilePhone);
		listLabels.put(Model.PERSONAL_HOME_PHONE, labelPersonalHomePhone);
		listLabels.put(Model.PRO_MOBILE_PHONE, labelProMobilePhone);
		listLabels.put(Model.PRO_OFFICE_PHONE, labelProOfficePhone);
		listLabels.put(Model.HOMEPAGE, labelHomePage);
		listLabels.put(Model.PRO_EMAIL, labelProEmail);
		listLabels.put(Model.PERSONAL_EMAIL, labelPersonalEmail);
		listLabels.put(Model.OTHER_IM, labelOtherIM);
		listLabels.put(Model.OTHER_SKYPE, labelOtherSkype);
		listLabels.put(Model.GROUP, labelGroup);

	}

	public void loadTextFields()
	{

		loadLabels();

		JTextField firstName = new JTextField();
		JTextField lastName = new JTextField();
		JTextField homeAddress = new JTextField();
		JTextField companyAddress = new JTextField();
		JTextField personalMobilePhone= new JTextField();
		JTextField personalHomePhone = new JTextField();
		JTextField proMobilePhone = new JTextField();
		JTextField proOfficePhone = new JTextField();
		JTextField homePage = new JTextField();
		JTextField proEmail = new JTextField();
		JTextField personalEmail = new JTextField();
		JTextField otherIM = new JTextField();
		JTextField otherSkype = new JTextField();
		JTextField group = new JTextField();

		listTextFields.put(Model.FIRST_NAME, firstName);
		listTextFields.put(Model.LAST_NAME, lastName);
		listTextFields.put(Model.HOME_ADDRESS, homeAddress);
		listTextFields.put(Model.COMPANY_ADDRESS, companyAddress);
		listTextFields.put(Model.PERSONAL_MOBILE_PHONE, personalMobilePhone);
		listTextFields.put(Model.PERSONAL_HOME_PHONE, personalHomePhone);
		listTextFields.put(Model.PRO_OFFICE_PHONE, proOfficePhone);
		listTextFields.put(Model.PRO_MOBILE_PHONE, proMobilePhone);
		listTextFields.put(Model.HOMEPAGE, homePage);
		listTextFields.put(Model.PRO_EMAIL, proEmail);
		listTextFields.put(Model.PERSONAL_EMAIL, personalEmail);
		listTextFields.put(Model.OTHER_IM, otherIM);
		listTextFields.put(Model.OTHER_SKYPE, otherSkype);
		listTextFields.put(Model.GROUP, group);
		//listTextFields.put(Model.PICTURE_PATH, picturePath);


		picturePath = new String("./images/download.jpeg");
	}

	public void loadButtons() {

		loadTextFields();

		Font police = new Font("Times News Roman", Font.BOLD, 20);

		buttonAddContact = new JButton();
		buttonAddContact.setFont(police);
		buttonAddContact.setText("Add");
		buttonAddContact.addActionListener(this);

		buttonSaveContact = new JButton();
		buttonSaveContact.setFont(police);
		buttonSaveContact.setText("Save");
		buttonSaveContact.addActionListener(this);

		buttonDeleteContact = new JButton();
		buttonDeleteContact.setFont(police);
		buttonDeleteContact.setText("Delete");
		buttonDeleteContact.addActionListener(this);

	}

	public void loadPanels() {

		loadButtons();
		final PersonalActionControler actionMethods = new PersonalActionControler();

		panelGeneral = new JPanel();
		panelPhoto = new JPanel();
		panelName = new JPanel();
		panelPhotoAndName = new JPanel();
		panelInfo = new JPanel();
		panelContactButtons = new JPanel();
		panelContact = new JPanel();
		panelList = new JPanel();
		panelListAndButtons = new JPanel();
		panelPersonalPhones = new JPanel();
		panelProPhones = new JPanel();
		panelEmail = new JPanel();
		panelOther = new JPanel();
		panelGroupAndHomePage = new JPanel();
		panelAddress = new JPanel();
		//panelCompanyAddress = new JPanel();

		panelGeneral.setLayout(new GridLayout(1,2));
		panelPhoto.setLayout(new GridLayout(1, 1));
		panelName.setLayout(new GridLayout(4,1));
		panelPhotoAndName.setLayout(new GridLayout(1,2));
		panelInfo.setLayout(new GridLayout(0,2));
		panelContactButtons.setLayout(new GridLayout(1,3));
		panelContact.setLayout(new GridLayout(0,1));
		panelList.setLayout(new GridLayout(0,1));
		panelListAndButtons.setSize(200, 350);
		panelListAndButtons.setLayout(new GridLayout(0,1));
		panelPersonalPhones.setLayout(new GridLayout(0,2));
		panelProPhones.setLayout(new GridLayout(0,2));
		panelEmail.setLayout(new GridLayout(0,2));
		panelOther.setLayout(new GridLayout(0,2));
		panelGroupAndHomePage.setLayout(new GridLayout(0,2));
		panelAddress.setLayout(new GridLayout(0,2));
		//panelCompanyAddress.setLayout(new GridLayout(0,2));


		GridBagConstraints gridBagConstraints = new GridBagConstraints();

		listLabels.get(Model.PERSONAL_MOBILE_PHONE).setText("Perso. Mobile Phone");
		panelPersonalPhones.add(listLabels.get(Model.PERSONAL_MOBILE_PHONE));
		panelPersonalPhones.add(listTextFields.get(Model.PERSONAL_MOBILE_PHONE));
		listLabels.get(Model.PERSONAL_HOME_PHONE).setText("Perso. Home Phone");
		panelPersonalPhones.add(listLabels.get(Model.PERSONAL_HOME_PHONE));
		panelPersonalPhones.add(listTextFields.get(Model.PERSONAL_HOME_PHONE));
		listLabels.get(Model.PRO_MOBILE_PHONE).setText("Pro. Mobile Phone");
		panelProPhones.add(listLabels.get(Model.PRO_MOBILE_PHONE));
		panelProPhones.add(listTextFields.get(Model.PRO_MOBILE_PHONE));
		listLabels.get(Model.PRO_OFFICE_PHONE).setText("Pro. Office Phone");
		panelProPhones.add(listLabels.get(Model.PRO_OFFICE_PHONE));
		panelProPhones.add(listTextFields.get(Model.PRO_OFFICE_PHONE));

		listLabels.get(Model.HOME_ADDRESS).setText("Home Address");
		panelAddress.add(listLabels.get(Model.HOME_ADDRESS));
		panelAddress.add(listTextFields.get(Model.HOME_ADDRESS));
		listLabels.get(Model.COMPANY_ADDRESS).setText("Company Address");
		panelAddress.add(listLabels.get(Model.COMPANY_ADDRESS));
		panelAddress.add(listTextFields.get(Model.COMPANY_ADDRESS));

		listLabels.get(Model.PERSONAL_EMAIL).setText("Perso. Email");
		panelEmail.add(listLabels.get(Model.PERSONAL_EMAIL));
		panelEmail.add(listTextFields.get(Model.PERSONAL_EMAIL));
		listLabels.get(Model.PRO_EMAIL).setText("Pro. Email");
		panelEmail.add(listLabels.get(Model.PRO_EMAIL));
		panelEmail.add(listTextFields.get(Model.PRO_EMAIL));

		listLabels.get(Model.OTHER_SKYPE).setText("Skype ID");
		panelOther.add(listLabels.get(Model.OTHER_SKYPE));
		panelOther.add(listTextFields.get(Model.OTHER_SKYPE));
		listLabels.get(Model.OTHER_IM).setText("Other (IM)");
		panelOther.add(listLabels.get(Model.OTHER_IM));
		panelOther.add(listTextFields.get(Model.OTHER_IM));

		listLabels.get(Model.FIRST_NAME).setText("First Name");
		panelName.add(listLabels.get(Model.FIRST_NAME));
		panelName.add(listTextFields.get(Model.FIRST_NAME));
		listLabels.get(Model.LAST_NAME).setText("Last Name");
		panelName.add(listLabels.get(Model.LAST_NAME));
		panelName.add(listTextFields.get(Model.LAST_NAME));

		listLabels.get(Model.HOMEPAGE).addMouseListener(new MouseListener(){


			@Override
			public void mouseClicked(MouseEvent e) {
				listTextFields = actionMethods.sendToHomePage(listTextFields);
			}

			@Override
			public void mousePressed(MouseEvent e) {
				// TODO Auto-generated method stub

			}

			@Override
			public void mouseReleased(MouseEvent e) {
				// TODO Auto-generated method stub

			}

			@Override
			public void mouseEntered(MouseEvent e) {
				// TODO Auto-generated method stub

			}

			@Override
			public void mouseExited(MouseEvent e) {
				// TODO Auto-generated method stub

			}

		});

		listLabels.get(Model.HOMEPAGE).setText("HomePage/WebPage");
		panelGroupAndHomePage.add(listLabels.get(Model.HOMEPAGE));
		panelGroupAndHomePage.add(listTextFields.get(Model.HOMEPAGE));
		listLabels.get(Model.GROUP).setText("Group:");
		panelGroupAndHomePage.add(listLabels.get(Model.GROUP));
		panelGroupAndHomePage.add(listTextFields.get(Model.GROUP));

		try {
			profilePicture = ImageIO.read(new File(picturePath));

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		labelProfilePicture = new JLabel(new ImageIcon(profilePicture));
		labelProfilePicture.setSize(110, 110);
		labelProfilePicture.addMouseListener(new MouseListener(){

			@Override
			public void mouseClicked(MouseEvent e) {

				JFileChooser chooser = new JFileChooser();
				FileNameExtensionFilter filter = new FileNameExtensionFilter(
						"JPG & GIF Images", "jpg", "gif", "jpeg");
				chooser.setFileFilter(filter);
				chooser.setVisible(true);
				int returnVal = chooser.showOpenDialog(labelProfilePicture);
				if(returnVal == JFileChooser.APPROVE_OPTION) 
				{
					System.out.println("You chose to open this file: " +
							chooser.getSelectedFile());
					picturePath = chooser.getSelectedFile().toString();
					try {
						File image = new File(picturePath);
						profilePicture = ImageIO.read(image);
						Image profileImage = profilePicture.getScaledInstance(110, 110, Image.SCALE_FAST);
						ImageIcon profileIcon = new ImageIcon(profileImage);
						//labelProfilePicture.setSize(110, 110);
						labelProfilePicture.setIcon(profileIcon);
						String extension = "";

						int i = picturePath.lastIndexOf('.');
						if (i > 0) {
						    extension = picturePath.substring(i+1);
						}
						String nameOfContact = (String) table.getValueAt(table.getSelectedRow(), 0);
						File copiedImage = new File("images/contacts/"+nameOfContact+"."+extension);
						Model.copyFileUsingFileStreams(image, copiedImage);
						picturePath = copiedImage.toString();
						
						
					} catch (IOException ioe) {
						// TODO Auto-generated catch block
						ioe.printStackTrace();
					}
				}

			}

			@Override
			public void mousePressed(MouseEvent e) {
				// TODO Auto-generated method stub

			}

			@Override
			public void mouseReleased(MouseEvent e) {
				// TODO Auto-generated method stub

			}

			@Override
			public void mouseEntered(MouseEvent e) {
				// TODO Auto-generated method stub

			}

			@Override
			public void mouseExited(MouseEvent e) {
				// TODO Auto-generated method stub

			}

		});

		panelPhoto.add(labelProfilePicture);

		panelPhotoAndName.add(panelPhoto);
		panelPhotoAndName.add(panelName);

		panelContactButtons.add(buttonAddContact);
		panelContactButtons.add(buttonSaveContact);
		panelContactButtons.add(buttonDeleteContact);

		panelContact.add(panelPhotoAndName);
		panelContact.add(panelPersonalPhones);
		panelContact.add(panelProPhones);
		panelContact.add(panelAddress);
		//panelContact.add(panelCompanyAddress);
		panelContact.add(panelEmail);
		panelContact.add(panelOther);
		panelContact.add(panelGroupAndHomePage);
		panelContact.add(panelContactButtons);

		//panelListAndButtons.add(panelListOrderButtons);
		contactList listContacts = new contactList();
		listOfContacts = listContacts.load();
		scrollingContactList = new JScrollPane();
		for (int i = 0; i < listOfContacts.size(); i++)
		{
			labelContact = new JLabel();
			Contact contactTest = (Contact) listOfContacts.get(i);
			labelContact.setText(contactTest.listContactField.get(Model.FIRST_NAME) 
					+ " " + contactTest.listContactField.get(Model.LAST_NAME) );
			scrollingContactList.add(labelContact);
		}

		String[] header = {"Name", "Group", "Date Added/Last Modified"};
		String[][] data = new String[listOfContacts.size()][3];
		for (int j=0; j<listOfContacts.size(); j++) {
			labelContact = new JLabel();
			Contact contactTest = (Contact) listOfContacts.get(j);
			data[j][0] = contactTest.listContactField.get(Model.FIRST_NAME) 
					+ " " + contactTest.listContactField.get(Model.LAST_NAME);
			data[j][1] = contactTest.listContactField.get(Model.GROUP);
			data[j][2] = contactTest.dateAdded;
		}

		model = new DefaultTableModel(data, header);
		table = new JTable(model);
		//table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		table.getColumnModel().getColumn(0).setPreferredWidth(125);
		table.getColumnModel().getColumn(1).setPreferredWidth(50);
		table.getColumnModel().getColumn(2).setPreferredWidth(225);
		table.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
			@Override
			public void valueChanged(ListSelectionEvent e) {
				int selectedRow = table.getSelectedRow();
				if (selectedRow != -1)
					changeContactDisplay((String) table.getValueAt(table.getSelectedRow(), 2));
			}
		});

		try {
			// 1.6+
			table.setAutoCreateRowSorter(true);
		} catch(Exception continuewithNoSort) {
		}
		JScrollPane tableScroll = new JScrollPane(table);

		JButton test = new JButton();
		test.setText("Test");
		panelList.add(test);
		scrollingContactList.add(panelList);
		panelListAndButtons.add(tableScroll);
		//panelListAndButtons.add(scrollingContactList);
		scrollingContactList.setPreferredSize(new Dimension(250,120));
		//panelListAndButtons.add(panelList);
		scrollingContactList.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		buttonAddContact.setSize(WIDTH, 40);
		//panelListAndButtons.add(buttonAddContact);

		panelGeneral.add(panelListAndButtons);
		panelGeneral.add(panelContact);


	}

	public void display() {

		Cwindow window = new Cwindow();
		window.setSize(800, 600);
		window.setTitle("Address Book");

		loadPanels();

		window.add(panelGeneral);

		window.setVisible(true);
		window.setLocationRelativeTo(null);
		window.setDefaultCloseOperation(EXIT_ON_CLOSE);


	}

	public void changeContactDisplay(String dateAdded) {
		for (int i = 0; i < listOfContacts.size(); i++)
		{
			Contact comparingContact = (Contact) listOfContacts.get(i);
			if(comparingContact.dateAdded == dateAdded)
			{
				i = listOfContacts.size()+1;

				for (final Entry<String, String> entry : comparingContact.listContactField.entrySet())
				{
					if(!entry.getValue().contentEquals("NULL"))
					{
						if(entry.getKey() == Model.PICTURE_PATH)
						{
							try {
								profilePicture = ImageIO.read(new File("images/loading_icon.png"));
								Image profileImage = profilePicture.getScaledInstance(110, 110, Image.SCALE_FAST);
								ImageIcon profileIcon = new ImageIcon(profileImage);
								labelProfilePicture.setIcon(profileIcon);
							} catch (IOException e1) {
								// TODO Auto-generated catch block
								e1.printStackTrace();
							}
							
							SwingUtilities.invokeLater(new Runnable() {

								@Override
								public void run() {
									try {
										profilePicture = ImageIO.read(new File(entry.getValue()));
										Image profileImage = profilePicture.getScaledInstance(110, 110, Image.SCALE_FAST);
										ImageIcon profileIcon = new ImageIcon(profileImage);
										labelProfilePicture.setIcon(profileIcon);
									} catch (IOException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
								}
							});
							
						}
						else
						{
							listTextFields.get(entry.getKey()).setText(entry.getValue());
						}
					}
				}
			}
		}
	}

	/**
	 * Fonction actionPerformed qui gère les actions des divers évènements
	 * @param e 
	 */
	public void actionPerformed(ActionEvent e) {

		if (e.getActionCommand().equals("Add")) {
			for (Entry<String, JTextField> entry : listTextFields.entrySet())
			{
				entry.getValue().setText("");
			}

			try {
				picturePath = "./images/download.jpeg";
				profilePicture = ImageIO.read(new File(picturePath));
				Image profileImage = profilePicture.getScaledInstance(110, 110, Image.SCALE_FAST);
				ImageIcon profileIcon = new ImageIcon(profileImage);
				labelProfilePicture.setIcon(profileIcon);
			} catch (IOException ioe) {
				// TODO Auto-generated catch block
				ioe.printStackTrace();
			}
			SwingUtilities.invokeLater(new Runnable() {

				@Override
				public void run() {
					table.getSelectionModel().clearSelection();
				}
			});

			//table.clearSelection();

		}

		if (e.getActionCommand().equals("Save")) {
			int nullValues = 0;
			int selectedRow = table.getSelectedRow();
			Contact savingContact = new Contact();
			Date d = new Date();
			for (int i = 0; i < listOfContacts.size(); i++)
			{
				Contact comparingContact = (Contact) listOfContacts.get(i);
				if(comparingContact.dateAdded == d.toString())
				{
					try {
						wait(1000);
					} catch (InterruptedException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					i = listOfContacts.size();
				}
			}

			for (Entry<String, String> entry : savingContact.listContactField.entrySet())
			{
				//System.out.println(entry.getKey());
				if(!entry.getKey().contains("picturePath"))//Don't do it for the picture since it's not in the HashMap
				{
					if (listTextFields.get(entry.getKey()).getText().isEmpty())
					{
						entry.setValue("NULL");
						nullValues++;
					}
					else
						entry.setValue(listTextFields.get(entry.getKey()).getText());
				}
			}

			savingContact.listContactField.put(Model.PICTURE_PATH, picturePath); // Picture save here
			System.out.println(picturePath);
			if (selectedRow == -1)
			{
				if (nullValues < 13)
				{
					savingContact.saveContact();
					model.addRow(new Object[]{(savingContact.listContactField.get(Model.FIRST_NAME) 
							+ " " + savingContact.listContactField.get(Model.LAST_NAME)), 
							savingContact.listContactField.get(Model.GROUP), 
							savingContact.dateAdded});
				}
			}
			else
			{
				System.out.println("modify" + selectedRow);
				String date = (String) table.getValueAt(selectedRow, 2);
				savingContact.modify(date);
				if (selectedRow != -1)
				{
					table.clearSelection();
					model.removeRow(selectedRow);
					model.addRow(new Object[]{(savingContact.listContactField.get(Model.FIRST_NAME) 
							+ " " + savingContact.listContactField.get(Model.LAST_NAME)), 
							savingContact.listContactField.get(Model.GROUP), 
							savingContact.dateAdded});
				}
			}

		}
		if (e.getActionCommand().equals("Delete")) {
			int selectedRow = table.getSelectedRow();
			if (selectedRow != -1){
				System.out.println("delete" + table.getSelectedRow());
				String date = (String) table.getValueAt(selectedRow, 2);
				Contact dummy = new Contact();
				dummy.delete(date);
	
				table.clearSelection();
			
				model.removeRow(selectedRow);
			}

		}

	}
}
